package com.zxp.common.core.security.authentication.mobile;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.Assert;

/**
 * 认证提供者
 * @author shollin
 * @desc
 * @date 2021/7/8/008 16:13
 */
@Slf4j
@RequiredArgsConstructor
public class MobileAuthenticationProvider implements AuthenticationProvider {

    private final UserDetailsService userDetailsService;

    /**
     * 处理认证，返回一个UserDetails, 参考源码： AbstractUserDetailsAuthenticationProvider
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        UserDetails user = userDetailsService.loadUserByUsername( (String)authentication.getPrincipal() );
        if(ObjectUtil.isEmpty(user)){
            throw new InternalAuthenticationServiceException("无法获取到用户信息");
        }

        MobileAuthenticationToken token = new MobileAuthenticationToken(user,user.getAuthorities());
        token.setDetails(authentication.getDetails());
        return token;
    }

    // 匹配哪一个token，进行处理
    @Override
    public boolean supports(Class<?> authentication) {
        return MobileAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
